Skip to content

Latest commit

 

History

History
67 lines (54 loc) · 1.26 KB

File metadata and controls

67 lines (54 loc) · 1.26 KB

633. Sum of Square Numbers

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.

Example 1:

Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5 

Example 2:

Input: 3 Output: False 

Solutions (Rust)

1. HashMap

use std::collections::HashSet;implSolution{pubfnjudge_square_sum(c:i32) -> bool{letmut b2 = HashSet::new();letmut a = 0_i32;whileletSome(a2) = a.checked_mul(a){if a2 > c {break;} b2.insert(a2);if b2.contains(&(c - a2)){returntrue;} a += 1;}false}}

2. Two Pointers

implSolution{pubfnjudge_square_sum(c:i32) -> bool{letmut a = 0;letmut b = c.min(46340);while a <= b {if c - b * b > a * a { a += 1;}elseif c - b * b < a * a { b -= 1;}else{returntrue;}}false}}
close